package com.lingx.web.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;

/**
 * Web 服务器类
 * 
 */
public final class ApiServer implements Runnable {
    
    private final static Logger logger = LoggerFactory.getLogger(ApiServer.class);
    
    /**
     * 监听端口号
     */
    private int port = 0;
    
    /**
     * Boss线程数
     */
    private int bossThreads = 1;
    
    /**
     * Worker线程数
     */
    private int workerThreads = 2;
    
    /**
     * Http 最大内容长度，默认为10M。
     */
    private int maxContentLength = 1024 * 1024 * 10;
    
    public ApiServer(int port) {
        this.port = port;
        int N_CPUS = Runtime.getRuntime().availableProcessors();
        this.bossThreads=N_CPUS*2;
        this.workerThreads=bossThreads*2;
        System.out.println("LINGX API Server =>bossThreads:"+bossThreads+",workerThreads:"+workerThreads);
    }
    
    public int getBossThreads() {
        return this.bossThreads;
    }
    public void setBossThreads(int threads) {
        this.bossThreads = threads;
    }
    
    public int getWorkerThreads() {
        return this.workerThreads;
    }
    public void setWorkerThreads(int threads) {
        this.workerThreads = threads;
    }
    
    public int getMaxContentLength() {
        return this.maxContentLength;
    }
    public void setMaxContentLength(int maxContentLength) {
        this.maxContentLength = maxContentLength;
    }
    
    /**
     * 启动服务
     * @throws InterruptedException 
     */
    public void startup() throws InterruptedException {
        
        // BossGroup处理nio的Accept事件（TCP连接）
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.bossThreads,new DefaultThreadFactory("LINGX_API_BossGroup"));
        // Worker处理nio的Read和Write事件（通道的I/O事件）
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(this.workerThreads,new DefaultThreadFactory("LINGX_API_BossGroup"));
        
        try {
            // handler在初始化时就会执行，而childHandler会在客户端成功connect后才执行。
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)       
            .childHandler(new HandlerInitializer(this.maxContentLength));
            
            ChannelFuture f = bootstrap.bind(port).sync();
            logger.info("LINGX-API端口监听 {}", this.port); 
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

	@Override
	public void run() {
		try {
			startup();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
